#!/usr/bin/python
#coding=utf-8

from gdata.finance.service import  FinanceService, PortfolioQuery, PositionQuery
from gdata.calendar.service import CalendarService
from gdata.finance import  PortfolioEntry, PortfolioData, TransactionEntry, TransactionData,  Price, Commission, Money
import atom.service
import gdata.calendar
import atom
import gdata
import time
import datetime
import sys
from PyFetion import PyFetion,sys_encoding

class Financer:
    def __init__(self,email,password):
        self.email = email
        self.password = password
        self.financeservice = FinanceService()

    def QueryTicker(self,ticker):
        self.financeservice.ClientLogin(self.email,self.password)
        query = PositionQuery()
        query.returns = False
        query.transactions = False
        try:
            pos = self.financeservice.GetPosition(3,ticker,query)
        except gdata.service.RequestError:
            txn = TransactionEntry(transaction_data=TransactionData(type='Buy',
                    date=None, shares='100', notes=None, price=None,
                    commission=None))
            self.financeservice.AddTransaction(txn,portfolio_id=3,ticker_id=ticker)
            pos =  self.financeservice.GetPosition(3,ticker,query)
        d = pos.position_data
        if int(float(d.shares)) == 0:
            return 0
        return (float(d.gain.money[0].amount)+float(d.cost_basis.money[0].amount))/float(d.shares)


class Reminder:
    def __init__(self,email,password):
        self.email = email
        self.password = password
        self.calendarservice = CalendarService()
        
    def SendSMS(self,msg):
        self.calendarservice.email = self.email
        self.calendarservice.password = self.password
        self.calendarservice.ProgrammaticLogin()
        event = gdata.calendar.CalendarEventEntry()
        event.title = atom.Title(text=msg)
        start_time = time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.gmtime(time.time() + 65))
        end_time = time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.gmtime(time.time() + 600))
        event.when.append(gdata.calendar.When(start_time=start_time, end_time=end_time))
        event.when[0].reminder.append(gdata.calendar.Reminder(minutes=1, method='sms'))
        event = self.calendarservice.InsertEvent(event, '/calendar/feeds/default/private/full')

if __name__ == '__main__':
    email = ''
    password = ''
    fr =  Financer(email,password)
#add new transaction here
#(code,count,costs,[low_warning,high_warning])
    tks = (('SHA:600016',500,7.926,[7.83,8.10]),
           ('SHE:000762',200,22.3,[21.8,23.50]))
    msg = ''
    for tk_info in tks:
        price = fr.QueryTicker(tk_info[0])
        if price == 0:
            continue
        if price > tk_info[3][1]:
            msg += 'high %s %f,gain %f\n '%(tk_info[0],price,tk_info[1]*(price-tk_info[2]))
        elif price < tk_info[3][0]:
            msg += 'low %s %f,gain %f\n '%(tk_info[0],price,tk_info[1]*(price-tk_info[2]))

    if msg != '':
        phone = PyFetion("15801207407","<password>","TCP")
        try:
            phone.login()
        except PyFetionSupportError,e:
            print u"手机号未开通飞信".encode(sys_encoding)
            sys.exit(0)
        except PyFetionAuthError,e:
            print u"手机号密码错误".encode(sys_encoding)
            sys.exit(0)

        if phone.login_ok:
            print u"登录成功".encode(sys_encoding)
        phone.send_sms(msg,to="15801207407")
